import { fetchPublicKey, fetchUserInfo, login, logout } from '@/api/auth'

export default {
  namespaced: true,
  state: {
    publicKey: '',
    userInfo: null
  },
  getters: {
    publicKey: state => state.publicKey,
    userInfo: state => state.userInfo,
  },
  mutations: {
    setPublicKey: (state, val) => {
      state.publicKey = val
    },
    setUserInfo: (state, val) => {
      state.userInfo = val
    }
  },
  actions: {
    fetchPublicKey: ({ commit }) => {
      return new Promise((reslove, reject) => {
        fetchPublicKey().then(key => {
          commit('setPublicKey', key)
          reslove(key)
        }).catch(reject)
      })
    },
    fetchUserInfo: ({ commit }) => {
      return new Promise((reslove, reject) => {
        fetchUserInfo().then(data => {
          if (data.logged_in) {
            const info = data.info
            commit('setUserInfo', info)
            reslove(info)
          }
          reslove(null)
        }).catch(reject)
      })
    },
    login: ({ getters, commit }, payload) => {
      const username = payload.username
      const password = payload.password
      const publicKey = getters.publicKey
      return new Promise((reslove, reject) => {
        login(username, password, publicKey).then(info => {
          commit('setUserInfo', info)
          reslove(info)
        }).catch(reject)
      })
    },
    logout: ({ commit }) => {
      return new Promise((reslove, reject) => {
        logout().then(() => {
          commit('setUserInfo', null)
          reslove()
        }).catch(reject)
      })
    }
  }
}
